package cn.edu.sjtu.process_management.util;

import cn.edu.sjtu.process_management.constant.RespStatus;
import cn.edu.sjtu.process_management.exception.model.OperatorException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ResponseUtil {

    /**
     * simplify the response from pydeploy
     *
     * @param ecnInfo the info of ecn
     * @return simplified response
     */
    public static JSONObject simplifyResp(JSONObject ecnInfo, String instanceId) {
        if (ecnInfo == null) return new JSONObject();
        String status = ecnInfo.getString("status");
        if (ecnInfo.getJSONObject("data") == null) return new JSONObject();
        if ("200".equals(status)) {
            // when use getXXX, it seems to be deserialized from string
            // remove the status and message field
            JSONObject ret = ecnInfo.fluentRemove("status").fluentRemove("message").getJSONObject("data");
            ret.put("instanceId", instanceId);
            // get the apis field, then remove it from ret
            JSONArray apis = ret.getJSONArray("apis");
            ret.put("apis", new JSONArray());
            // remove method, params, responses field of apis
            // and add the removed one to ret
            JSONObject tmp;
            for (int i = 0; i < apis.size(); i++) {
                tmp = apis.getJSONObject(i);
                tmp.fluentRemove("method").fluentRemove("params").fluentRemove("responses");
                ret.getJSONArray("apis").add(tmp);
            }
            return ret;
        } else if ("404".equals(status)) {
            return new JSONObject();
        } else {
            throw new OperatorException(RespStatus.OPERATOR_SET_ERROR);
        }
    }
}
